﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GoogleEarthHelper;
using EARTHLib;
using System.Runtime.InteropServices;
using System.IO;
using KorTransLib;
using Gma.UserActivityMonitor;

namespace KorTrans
{
    public partial class frmKorTrans : Form
    {
        #region "PInvokes"
        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;

            public POINT(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }

            public static implicit operator System.Drawing.Point(POINT p)
            {
                return new System.Drawing.Point(p.X, p.Y);
            }

            public static implicit operator POINT(System.Drawing.Point p)
            {
                return new POINT(p.X, p.Y);
            }
        }
        [Serializable, StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;

            public RECT(int left_, int top_, int right_, int bottom_)
            {
                Left = left_;
                Top = top_;
                Right = right_;
                Bottom = bottom_;
            }

            public int Height { get { return Bottom - Top; } }
            public int Width { get { return Right - Left; } }
            public Size Size { get { return new Size(Width, Height); } }

            public Point Location { get { return new Point(Left, Top); } }

            // Handy method for converting to a System.Drawing.Rectangle
            public Rectangle ToRectangle()
            { return Rectangle.FromLTRB(Left, Top, Right, Bottom); }

            public static RECT FromRectangle(Rectangle rectangle)
            {
                return new RECT(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom);
            }

            public override int GetHashCode()
            {
                return Left ^ ((Top << 13) | (Top >> 0x13))
                  ^ ((Width << 0x1a) | (Width >> 6))
                  ^ ((Height << 7) | (Height >> 0x19));
            }

            #region Operator overloads

            public static implicit operator Rectangle(RECT rect)
            {
                return rect.ToRectangle();
            }

            public static implicit operator RECT(Rectangle rect)
            {
                return FromRectangle(rect);
            }

            #endregion
        }


        [DllImport("user32.dll")]
        static extern IntPtr WindowFromPoint(POINT Point);

        [DllImport("user32.dll")]
        static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [DllImport("user32.dll")]
        static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);

        #endregion

        int hWndRender = 0;

        public frmKorTrans()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            /*
            Pafta p = Pafta.PaftaGetir("F22-b3");
            Pafta p1 = Pafta.PaftaGetir("F19-b3");
            Pafta p3 = Pafta.PaftaGetir("İSTANBUL-F22");
            Pafta p4 = Pafta.PaftaGetir("ELBİŞTAN-F22");
            propertyGrid1.SelectedObject = p4;
            string s;
            Pafta.PaftaBul(100000, p4.Merkez(), out s);
            testUTMTransform();
            return;
            */
            /*CoordinateConverterMath uc = new CoordinateConverterMath();
            DegreeMinuteSecondCoordinate dms = new DegreeMinuteSecondCoordinate();
            dms.latDegree = 41;
            dms.latMinute = 14;
            dms.latSecond = 50.68;
            dms.lonDegree = 28;
            dms.lonMinute = 57;
            dms.lonSecond = 21.43;

            UTMCoordinate utm = new UTMCoordinate();
            utm.Zone = "35T";
            utm.Sağa = 663890;
            utm.Yukarı = 4568130;

            UTMCoordinate utmCoord = utm;*/
        }

        private void testUTMTransform()
        {
            UTMCoordinate utm = new UTMCoordinate();
            DegreeMinuteSecondCoordinate dms = new DegreeMinuteSecondCoordinate();
            DecimalDegreeCoordinate dd = new DecimalDegreeCoordinate();
            CoordinateConverterMath cc = new CoordinateConverterMath();
            UTMCoordinate utm2 = new UTMCoordinate();
            utm.Zone = "35T";

            for (int sağa = 663880; sağa <= 663895; sağa++)
                for (int yukarı = 4568060; yukarı <= 4568075; yukarı++)
                {
                    utm.Sağa = sağa;
                    utm.Yukarı = yukarı;
                    dd = CoordinateConverterMath.UTMtoDD(utm);
                    utm2 = CoordinateConverterMath.DDtoUTM(dd);
                    //listBox1.Items.Add(string.Format("{0:N12}\t{1:N12}", utm.Sağa - utm2.Sağa, utm.Yukarı - utm2.Yukarı));
                }
        }

        IApplicationGE ige;

        private void button2_Click(object sender, EventArgs e)
        {
            //string PaftaAdı;
            /*
            Pafta p = Pafta.PaftaBul(25000, new UTMCoordinate("35T", 663886, 4568067), out PaftaAdı);
            
            Pafta pr = Pafta.PaftaBul(2500, new UTMCoordinate("35T", 663886, 4568067), out PaftaAdı);
            Pafta pr2 = Pafta.PaftaGetir(PaftaAdı);
            Pafta pr3 = Pafta.PaftaBul(2500, pr2.Merkez(), out PaftaAdı);

            Pafta p1 = Pafta.PaftaGetir("BURSA-G22-a");
            Pafta ps1 = Pafta.PaftaGetir("BURSA-G22-a-07-a-A");
            Pafta psg1 = Pafta.PaftaGetir("BURSA-G22-09-a");
            
            
            //İSTANBUL-F21-c-05-a-A

            Pafta p2 = Pafta.PaftaBul(10000, new DecimalDegreeCoordinate(40.99, 29.01), out PaftaAdı);
            
            Pafta p3=Pafta.PaftaGetir(Pafta.paftaİsimleri()[4]);

            //p.paftaBölümü(p, 2, 3, 1, 1, out ddGüneyBatı, out ddKuzeyDoğu);
            */
            /*
            Pafta pİzmir = Pafta.PaftaGetir("İZMİR");
            Pafta pİstanbul = Pafta.PaftaGetir("İSTANBUL");

            Coordinate c1 = pİzmir.Merkez();
            Coordinate c2 = pİstanbul.Merkez();

            double d = Jeodezi.distVincenty(c1, c2);
            TypeConverter corcon = TypeDescriptor.GetConverter(typeof(DegreeMinuteSecondCoordinate));
            DegreeMinuteSecondCoordinate dm1 = (DegreeMinuteSecondCoordinate)corcon.ConvertFrom(c1);
            DegreeMinuteSecondCoordinate dm2 = (DegreeMinuteSecondCoordinate)corcon.ConvertFrom(c2);
            listBox1.Items.Add(dm1);
            listBox1.Items.Add(dm2);
            listBox1.Items.Add(d);


            // Flinders Peak    37°57′03.72030″S, 144°25′29.52440″E
            // Buninyong 	     37°39′10.15610″S, 143°55′35.38390″E
            c1 = new DegreeMinuteSecondCoordinate(37, 57, 3.72030, 144, 25, 29.5244);
            c2 = new DegreeMinuteSecondCoordinate(37, 39, 10.1561, 143, 55, 35.3839);
            d = Jeodezi.distVincenty(c1, c2);

            listBox1.Items.Add(c1);
            listBox1.Items.Add(c2);
            listBox1.Items.Add(d);
              */

        }

        Queue<PointF> qPoints = new Queue<PointF>();

        private void frmKorTrans_Load(object sender, EventArgs e)
        {
            cmbPaftaÖlçekSayısı.SelectedIndex = 3;
            cmbPaftaAdı.Items.AddRange(Pafta.paftaİsimleri().ToArray());
            // point queue worker
            BackgroundWorker bwPointQueue = new BackgroundWorker();
            bwPointQueue.DoWork += new DoWorkEventHandler(bwPointQueue_DoWork);
            bwPointQueue.RunWorkerAsync();
        }

        bool bwRequestExit = false;
        void bwPointQueue_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!bwRequestExit)
            {
                while (qPoints.Count > 0)
                {
                    PointF pf;
                    lock (qPoints)
                    {
                        pf = qPoints.Dequeue();
                    }
                    PointOnTerrainGE po = ige.GetPointOnTerrainFromScreenCoords(pf.X, pf.Y);
                    PaftaGEHelper.GEShowNokta(ige, "Mouse Point", "", "", "", new DecimalDegreeCoordinate(po.Latitude, po.Longitude));
                }
                System.Threading.Thread.Sleep(500);
            }
        }

        void HookManager_MouseDown(object sender, MouseEventArgs e)
        {
            if (hWndRender == 0 || ige == null)
                return;
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
                POINT p = new POINT(e.X, e.Y);
                IntPtr hWnd = WindowFromPoint(p);
                if ((int)hWnd == hWndRender)
                {
                    //click is in render window
                    bool res = ScreenToClient(hWnd, ref p);
                    RECT rectRender;
                    res = GetWindowRect(hWnd, out rectRender);
                    float x = 2.0f * p.X / rectRender.Width - 1.0f;
                    float y = 1.0f - 2.0f * p.Y / rectRender.Height;
                    lock (qPoints)
                    {
                        qPoints.Enqueue(new PointF(x, y));
                    }
                }
            }
        }

        private DegreeMinuteSecondCoordinate getDMS()
        {
            DegreeMinuteSecondCoordinate ret = new DegreeMinuteSecondCoordinate();
            ret.latDegree = (int)nudDMSenlemDerece.Value;
            ret.latMinute = (int)nudDMSenlemDakika.Value;
            ret.latSecond = (double)nudDMSenlemSaniye.Value;
            ret.lonDegree = (int)nudDMSboylamDerece.Value;
            ret.lonMinute = (int)nudDMSboylamDakika.Value;
            ret.lonSecond = (double)nudDMSboylamSaniye.Value;
            return ret;
        }

        private void setDMS(DegreeMinuteSecondCoordinate dms)
        {
            DegreeMinuteSecondCoordinate ret = new DegreeMinuteSecondCoordinate();
            nudDMSenlemDerece.Value = dms.latDegree;
            nudDMSenlemDakika.Value = dms.latMinute;
            nudDMSenlemSaniye.Value = (decimal)dms.latSecond;
            nudDMSboylamDerece.Value = dms.lonDegree;
            nudDMSboylamDakika.Value = dms.lonMinute;
            nudDMSboylamSaniye.Value = (decimal)dms.lonSecond;
        }

        private DecimalDegreeCoordinate getDD()
        {
            DecimalDegreeCoordinate ret = new DecimalDegreeCoordinate();
            ret.lat = (double)nudDDenlem.Value;
            ret.lon = (double)nudDDboylam.Value;
            return ret;
        }

        private void setDD(DecimalDegreeCoordinate dd)
        {
            nudDDenlem.Value = (decimal)dd.lat;
            nudDDboylam.Value = (decimal)dd.lon;
        }

        private UTMCoordinate getUTM()
        {
            UTMCoordinate ret = new UTMCoordinate();
            ret.Zone = txtUTMzone.Text;
            ret.Sağa = (double)nudUTMsağa.Value;
            ret.Yukarı = (double)nudUTMyukarı.Value;
            return ret;
        }

        private void setUTM(UTMCoordinate utm)
        {
            txtUTMzone.Text = utm.Zone;
            nudUTMsağa.Value = (decimal)utm.Sağa;
            nudUTMyukarı.Value = (decimal)utm.Yukarı;
        }

        private void setPafta(Coordinate coord)
        {
            string paftaAdı;
            Pafta p = Pafta.PaftaBul(int.Parse(cmbPaftaÖlçekSayısı.Text), coord, out paftaAdı);
            cmbPaftaAdı.Text = paftaAdı;
            propertyGrid1.SelectedObject = p;
        }

        private Pafta getPafta(string paftaAdı)
        {
            Pafta p = Pafta.PaftaGetir(paftaAdı);
            cmbPaftaAdı.Text = p.PaftaAdı;
            propertyGrid1.SelectedObject = p;
            cmbPaftaÖlçekSayısı.SelectedItem = p.ÖlçekSayısı.ToString();
            return p;
        }

        /*
            DecimalDegreeCoordinate dd = (DecimalDegreeCoordinate)TypeDescriptor.GetConverter(typeof(DecimalDegreeCoordinate).ConvertFrom(utm));
            DegreeMinuteSecondCoordinate = (DegreeMinuteSecondCoordinate)TypeDescriptor.GetConverter(typeof(DegreeMinuteSecondCoordinate)).ConvertFrom(utm);
            UTMCoordinate = (UTMCoordinate)TypeDescriptor.GetConverter(typeof(UTMCoordinate)).ConvertFrom(utm);
         * */

        private void btnUTMdenDönüştür_Click(object sender, EventArgs e)
        {
            try
            {
                UTMCoordinate utm = getUTM();
                DecimalDegreeCoordinate dd = (DecimalDegreeCoordinate)TypeDescriptor.GetConverter(typeof(DecimalDegreeCoordinate)).ConvertFrom(utm);
                DegreeMinuteSecondCoordinate dms = (DegreeMinuteSecondCoordinate)TypeDescriptor.GetConverter(typeof(DegreeMinuteSecondCoordinate)).ConvertFrom(utm);
                setDD(dd);
                setDMS(dms);
                setPafta(utm);
            }
            catch (ArgumentException ae)
            {
                MessageBox.Show(ae.Message);
                txtUTMzone.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDMSdenDönüştür_Click(object sender, EventArgs e)
        {
            try
            {
                DegreeMinuteSecondCoordinate dms = getDMS();
                DecimalDegreeCoordinate dd = (DecimalDegreeCoordinate)TypeDescriptor.GetConverter(typeof(DecimalDegreeCoordinate)).ConvertFrom(dms);
                UTMCoordinate utm = (UTMCoordinate)TypeDescriptor.GetConverter(typeof(UTMCoordinate)).ConvertFrom(dms);
                setDD(dd);
                setUTM(utm);
                setPafta(dms);
            }
            catch (ArgumentException ae)
            {
                MessageBox.Show(ae.Message);
                nudDMSenlemDerece.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDDdenDönüştür_Click(object sender, EventArgs e)
        {
            try
            {
                DecimalDegreeCoordinate dd = getDD();
                DegreeMinuteSecondCoordinate dms = (DegreeMinuteSecondCoordinate)TypeDescriptor.GetConverter(typeof(DegreeMinuteSecondCoordinate)).ConvertFrom(dd);
                UTMCoordinate utm = (UTMCoordinate)TypeDescriptor.GetConverter(typeof(UTMCoordinate)).ConvertFrom(dd);
                setUTM(utm);
                setDMS(dms);
                setPafta(dd);
            }
            catch (ArgumentException ae)
            {
                MessageBox.Show(ae.Message);
                txtUTMzone.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnPaftaGetir_Click(object sender, EventArgs e)
        {
            Pafta p = getPafta(cmbPaftaAdı.Text);
            Coordinate mrk = p.Merkez();
            setDD((DecimalDegreeCoordinate)TypeDescriptor.GetConverter(typeof(DecimalDegreeCoordinate)).ConvertFrom(mrk));
            setDMS((DegreeMinuteSecondCoordinate)TypeDescriptor.GetConverter(typeof(DegreeMinuteSecondCoordinate)).ConvertFrom(mrk));
            setUTM((UTMCoordinate)TypeDescriptor.GetConverter(typeof(UTMCoordinate)).ConvertFrom(mrk));

        }

        private void button3_Click(object sender, EventArgs e)
        {
            Bitmap bmp = new Bitmap(500, 500);
            Graphics g = Graphics.FromImage(bmp);
            float w = float.MinValue;
            string k = "";
            using (Font pngFont = new Font(FontFamily.GenericMonospace, 18, FontStyle.Bold))
            {
                List<string> lst = Pafta.paftaİsimleri();
                foreach (string s in lst)
                {
                    float t = g.MeasureString(s, pngFont).Width;
                    if (t > w)
                    {
                        w = t;
                        k = s;
                    }
                }
            }
            MessageBox.Show(k);
        }

        private void chkGEKullan_CheckedChanged(object sender, EventArgs e)
        {
            if (chkGEKullan.Checked)
            {
                //HookManager.MouseDown += new MouseEventHandler(HookManager_MouseDown);
                try
                {
                    ige = PaftaGEHelper.GEBaşlat();
                }
                catch (COMException ce)
                {
                    MessageBox.Show(string.Format("HRESULT:{0}\nMesaj:{1}", ce.ErrorCode, ce.Message));
                    return;
                }
                hWndRender = ige.GetRenderHwnd();
                //PaftaGEHelper.GEFocusTürkiye(ige);
            }
            else
            {
                //HookManager.MouseDown -= new MouseEventHandler(HookManager_MouseDown);
            }
        }



        private void btnGEPafta_Click(object sender, EventArgs e)
        {
            if (ige != null)
            {
                Pafta p = null;
                if (propertyGrid1.SelectedObject is Pafta)
                    p = (Pafta)propertyGrid1.SelectedObject;
                if (p != null)
                {
                    PaftaGEHelper.GEShowPafta(ige, p);
                    PaftaGEHelper.GEFocusPafta(ige, p);
                }
            }
        }



        private void btnGEUTM_Click(object sender, EventArgs e)
        {
            if (ige != null)
            {
                Coordinate c = getUTM();
                PaftaGEHelper.GEShowNokta(ige, "root", txtGEUTMNoktaAdı.Text, "", "", c);
                PaftaGEHelper.GEFocusNokta(ige, c);
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Ruhsat Markup Language|*.rml";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Ruhsat ruh = new Ruhsat();
                ruh.Load(ofd.FileName);
                PaftaGEHelper.GEShowRuhsat(ige, ruh.ToString(), ruh);
                ruh.Save("c:\\deneme.rml");
                return;
                List<UTMCoordinate> utms = new List<UTMCoordinate>();
                string[] lines = File.ReadAllLines(ofd.FileName);
                foreach (string s in lines)
                {
                    if (s.Length > 0)
                    {
                        string[] cols = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        utms.Add(new UTMCoordinate("35S", double.Parse(cols[1]), double.Parse(cols[2])));
                    }
                }
                PaftaGEHelper.GEShowPolygon(ige, "ruhsatDeneme", utms.ToArray());
            }
        }

        private void frmKorTrans_FormClosing(object sender, FormClosingEventArgs e)
        {
            bwRequestExit = true;
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            List<UTMCoordinate> lst = new List<UTMCoordinate>();
            /*lst.Add(new UTMCoordinate("35S", 10, 10));
            lst.Add(new UTMCoordinate("35S", 10, 13));
            lst.Add(new UTMCoordinate("35S", 14, 10));*/

            lst.Add(new UTMCoordinate("35S", 558360, 4216860));
            lst.Add(new UTMCoordinate("35S", 559050, 4217550));
            lst.Add(new UTMCoordinate("35S", 559100, 4217060));
            lst.Add(new UTMCoordinate("35S", 558670, 4216690));
            double area;
            PolygonArea.CalculateArea(lst, out area);
            double hektar = area / 10000;
            double cx, cy;
            double radius = Math.Sqrt(area / Math.PI);
            PolygonArea.CalculateCentroid(lst, out cx, out cy);
            PaftaGEHelper.GEShowPolygon(ige, "pafta", lst.ToArray());
            UTMCoordinate centroid = new UTMCoordinate(lst[0].Zone, cy, cx);
            PaftaGEHelper.GEShowNokta(ige, "", "", "", "", centroid);
            List<Coordinate> lstCor = GoogleEarthHelper.Geometry.GetCircleCoordinates(centroid, 60, radius);
            PaftaGEHelper.GEShowPolygon(ige, "deneme", lstCor.ToArray());

        }

        private double[,] normalize255(double[,] val, int m, int n)
        {
            double min = double.MaxValue;
            double max = double.MinValue;

            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                {
                    if (val[i, j] > max)
                        max = val[i, j];
                    if (val[i, j] < min)
                        min = val[i, j];
                }

            double[,] ret = new double[m, n];
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                {
                    ret[i, j] = 255 * (val[i, j] - min) / (max - min);
                }
            return ret;
        }

        private double[] normalize255(double[] val, int n)
        {
            double min = double.MaxValue;
            double max = double.MinValue;

            for (int j = 0; j < n; j++)
            {
                if (val[j] > max)
                    max = val[j];
                if (val[j] < min)
                    min = val[j];
            }

            double[] ret = new double[n];
            for (int j = 0; j < n; j++)
            {
                ret[j] = 255 * (val[j] - min) / (max - min);
            }
            return ret;
        }

        double[,] retF255;
        double[,] F255;

        private void KESİTTEST()
        {
            int hWndRender = ige.GetRenderHwnd();
            RECT renderRECT;
            GetWindowRect((IntPtr)hWndRender, out renderRECT);
            POINT p = new POINT(0, 0);

            int samplingScale = 15;

            int n = renderRECT.Height / samplingScale;

            /*
             * KESİT ALMA
             * 
             * */

            double[] xs = new double[renderRECT.Height / samplingScale];
            double[] ys = new double[renderRECT.Height / samplingScale];

            int i = 0;
            double minYukarı = double.MaxValue;
            double maxYukarı = double.MinValue;
            for (int j = 0; j < renderRECT.Height / samplingScale; j++)
            {
                p.X = i * samplingScale;
                p.Y = j * samplingScale;

                float x = 2.0f * p.X / renderRECT.Width - 1.0f;
                float y = 1.0f - 2.0f * p.Y / renderRECT.Height;

                PointOnTerrainGE pot = ige.GetPointOnTerrainFromScreenCoords(x, y);
                UTMCoordinate utm = (UTMCoordinate)TypeDescriptor.GetConverter(typeof(UTMCoordinate)).ConvertFrom(new DecimalDegreeCoordinate(pot.Latitude, pot.Longitude));

                xs[renderRECT.Height / samplingScale - j - 1] = utm.Yukarı;
                if (minYukarı > utm.Yukarı) minYukarı = utm.Yukarı;
                if (maxYukarı < utm.Yukarı) maxYukarı = utm.Yukarı;

                ys[j] = pot.Altitude;

            }

            double[] c = new double[0];
            Spline2d.spline3.buildcubicspline(xs, ys, n, 1, 0, 1, 0, ref c);

            double[] points = new double[1000];


            for (int k = 0; k < 1000; k++)
            {
                points[k] = Spline2d.spline3.splineinterpolation(ref c, k / 1000.0 * (maxYukarı - minYukarı) + minYukarı);
            }

            double[] points255 = normalize255(points, n);

            Form frm = new Form();
            frm.Width = 1000;//renderRECT.Width;
            frm.Height = 300;// renderRECT.Height;
            //frm.FormBorderStyle = FormBorderStyle.None;
            frm.TopMost = true;
            frm.Show(this);

            using (Graphics g = frm.CreateGraphics())
            {
                for (int j = 1; j < 1000; j++)
                {
                    g.DrawLine(Pens.Black, j - 1, (float)points[j - 1], j, (float)points[j]);
                }
            }

        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            int hWndRender = ige.GetRenderHwnd();
            RECT renderRECT;
            GetWindowRect((IntPtr)hWndRender, out renderRECT);
            POINT p = new POINT(0, 0);

            int samplingScale = 15;

            int m = renderRECT.Width / samplingScale;
            int n = renderRECT.Height / samplingScale;
            double[,] f = new double[m, n];

            for (int i = 0; i < renderRECT.Width / samplingScale; i++)
                for (int j = 0; j < renderRECT.Height / samplingScale; j++)
                {
                    p.X = i * samplingScale;
                    p.Y = j * samplingScale;

                    float x = 2.0f * p.X / renderRECT.Width - 1.0f;
                    float y = 1.0f - 2.0f * p.Y / renderRECT.Height;

                    PointOnTerrainGE pot = ige.GetPointOnTerrainFromScreenCoords(x, y);
                    f[i, j] = pot.Altitude;
                }

            F255 = normalize255(f, m, n);






            int retM = renderRECT.Width;
            int retN = renderRECT.Height;
            double[,] retF = new double[retM, retN];

            Spline2d.spline2d.bicubicresamplecartesian(ref f, m, n, ref retF, retM, retN);


            retF255 = normalize255(retF, retM, retN);

            Form frm = new Form();
            frm.Width = 1000;//renderRECT.Width;
            frm.Height = 300;// renderRECT.Height;
            frm.FormBorderStyle = FormBorderStyle.None;
            frm.TopMost = true;
            frm.Show(this);

            Brush[] bs = new Brush[256];
            for (int i = 0; i < 256; i++)
            {
                bs[i] = new SolidBrush(Color.FromArgb(i, 0, 0));
            }


            //draw retf
            using (Graphics g = frm.CreateGraphics())
            {
                for (int i = 0; i < retM; i++)
                    for (int j = 0; j < retN; j++)
                    {
                        g.FillRectangle(bs[(int)retF255[i, j]], i, j, 1, 1);
                    }
            }

            /*
            //draw f
            using (Graphics g = frm.CreateGraphics())
            {
                for (int i = 0; i < m; i++)
                    for (int j = 0; j < n; j++)
                    {
                        g.FillRectangle(bs[(int)F255[i, j]], i, j, 1, 1);
                    }
            }
             * */
        }

        private void button4_Click(object sender, EventArgs e)
        {
            KESİTTEST();
        }
    }
}
